package com.javaIO.chapter2;

import javax.swing.*;
import java.awt.*;
import java.io.OutputStream;


/**
 * 组件流, 你以为的控制台其实也是一个组件,
 * */
public class StreamedTextArea extends TextArea {

    OutputStream theOutput = new TextAreaOutputStream();
    public StreamedTextArea() {
        this("", 0, 0, SCROLLBARS_BOTH);
    }
    public StreamedTextArea(String text) {
        this(text, 0, 0, SCROLLBARS_BOTH);
    }
    public StreamedTextArea(int rows, int columns) {
        this("", rows, columns, SCROLLBARS_BOTH);
    }

    public StreamedTextArea(String text, int rows, int columns) {
        this(text, rows, columns, SCROLLBARS_BOTH);
    }
    public StreamedTextArea(String text, int rows, int columns, int  scrollbars) {
        super(text, rows, columns, scrollbars);
        setEditable(false);
    }
    public OutputStream getOutputStream() {
        return theOutput;
    }
    class TextAreaOutputStream extends OutputStream {
        public synchronized void write(int b) {
// recall that the int should really just be a byte
            b &= 0x000000FF;
// must convert byte to a char in order to append it
            char c = (char) b;
            append(String.valueOf(c));
        }
        public synchronized void write(byte[] data, int offset, int length) {
            append(new String(data, offset, length));
        }
    }

    public static void main(String[] args) throws InterruptedException {

        JFrame f=new JFrame("intellj idea ");
        Dimension d=new Dimension();
        d.setSize(800,600);
        f.setSize(d);        //设置组件大小
        f.setBackground(Color.WHITE);   //背景色设置为白色
        Point p=new Point(400,100);    //指定组件显示位置
        f.setLocation(p);     //设置组件显示位置
        f.setVisible(true);    //设置组件可见

        StreamedTextArea streamedTextArea = new StreamedTextArea("caonima" , 100, 100, 0);

        f.add(streamedTextArea);

        for (int i = 0; i < 10; i++) {
            streamedTextArea.append("shit ");
            Thread.sleep(2000);
        }

        System.exit(1);
    }


}
